package com.example.question.list.list2;

import com.example.question.list.list1.ListNode;

/**
 * @Date 2023-07-08
 * @Author Jonathan
 */
public class Code05_2 {
    public static void main(String[] args) {

    }

    /**
     * @param l1
     * @param l2
     * @return
     */
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode retHead = new ListNode(-1);
        ListNode retCur = retHead;
        // 进位
        int carry = 0;
        while (cur1 != null && cur2 != null) {
            int val = (cur1.val + cur2.val + carry) % 10;
            carry = (cur1.val + cur2.val + carry) / 10;
            retCur.next = new ListNode(val);
            retCur = retCur.next;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        while (cur1 != null) {
            int val = (cur1.val + carry) % 10;
            carry = (cur1.val + carry) / 10;
            retCur.next = new ListNode(val);
            retCur = retCur.next;
            cur1 = cur1.next;
        }

        while (cur2 != null) {
            int val = (cur2.val + carry) % 10;
            carry = (cur2.val + carry) / 10;
            retCur.next = new ListNode(val);
            retCur = retCur.next;
            cur2 = cur2.next;
        }
        // 最后一次还占用进位的话  还要新增一个节点
        if (carry > 0) {
            retCur.next = new ListNode(carry);
        }
        return retHead.next;
    }
}
